package com.apollo.es;

import com.alibaba.fastjson.JSON;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import util.FileUtil;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2018/2/3.
 */
public class RestTemplateTest {

    private static RestTemplate restTemplate = null;

    public static void initRest(){
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setReadTimeout(5000);//ms
        factory.setConnectTimeout(15000);//ms

        if(restTemplate == null){
            restTemplate = new RestTemplate();
        }

    }

    private static HttpEntity initHttp(Map<String,Object> map){
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());

        HttpEntity<String> formEntity = new HttpEntity<String>(JSON.toJSONString(map), headers);
        return formEntity;
    }


    public static void queryData(String indexName){
       String url ="http://monitor.qiaofangyun.com/elasticsearch/queryAll";
        //String url = "http://192.168.2.30:8083/elasticsearch/queryAll";
        initRest();
        Map<String,Object> map  = new HashMap<String,Object>();

        map.put("indexName",indexName);
        map.put("startTime", "2018-3-12 13:00:00");
        map.put("endTime","2018-3-12 17:12:10");
        map.put("page","1");
        map.put("size","1");
        map.put("typeName","logs");
        map.put("level","ERROR");
        map.put("env","gz-online");
         //map.put("thrown","Invalid");
        map.put("thrown","statement handle ");
        RestTemplate restTemplate = new RestTemplate();
        String result = restTemplate.postForObject(url, initHttp(map), String.class);

                if(!result.contains("\"data\":\\{\\}") && result.contains("traceId")){
                    FileUtil.writeFile(new File("e:/content.txt"),indexName+",c:"+result+"\r\n","utf-8");
                    System.out.println("------------------------indexName:" + indexName + ",result:" + result + "---------------------------------.");
                }else{
                    System.out.print("xc");
                }

    }

    public static void main(String[] args)throws  Exception{


//        ResponseEntity responseEntity = restTemplate.postForEntity(url,map,String.class);
//        System.out.print(responseEntity.getBody());
    }
}
